package AAAAAAA;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOTest {

    public static void writeByNIO(String path, String context) {
        FileOutputStream fos = null;
        FileChannel fc = null;

        try {
            fos = new FileOutputStream(path, true);
            fc = fos.getChannel();
            ByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5);

            for (int i = 0 ; i < 3 ; i++) {
                bb.put((context + "\n").getBytes());
            }

            bb.flip();
            fc.write(bb);
            bb.clear();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fc != null) {
                    fc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void readByNIO(String path) {
        FileInputStream fis = null;
        FileChannel fc = null;

        try {
            fis = new FileInputStream(path);
            fc = fis.getChannel();
            ByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5);
            int length;

            while ((length = fc.read(bb)) != -1) {
                bb.flip();
                System.out.println(new String(bb.array(), 0 , length));
                bb.clear();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fc != null) {
                    fc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
